package com.dcy.gateway.config;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author dcy
 * @description Swagger资源配置
 * @createTime 2023/1/2 15:33
 */
@Profile({"local", "default", "dev", "test"})
@Component
@RequiredArgsConstructor
public class SwaggerResourceConfig implements SwaggerResourcesProvider {

    private static final String URI = "/v2/api-docs";
    private static final String NACOS_DEFAULT_SPRING_CLOUD_KEY = "SPRING_CLOUD";
    private static final String NACOS_DEFAULT_SPRING_CLOUD_FLAG = "preserved.register.source";
    private static final String NACOS_DEFAULT_SWAGGER_VERSION = "1.0";
    private final RouteLocator routeLocator;
    @Value("${spring.application.name}")
    private String applicationName;

    /**
     * 获取swagger资源列表
     *
     * @return
     */
    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> resources = new ArrayList<>();
        routeLocator.getRoutes().subscribe(route -> {
            final Map<String, Object> metadata = route.getMetadata();
            // 只过滤spring-cloud项目  和  不是网关服务(自己)
            if (NACOS_DEFAULT_SPRING_CLOUD_KEY.equals(MapUtil.getStr(metadata, NACOS_DEFAULT_SPRING_CLOUD_FLAG))
                    && !StrUtil.equals(applicationName, route.getUri().getHost())) {
                resources.add(swaggerResource(route.getUri().getHost(), route.getUri().getHost() + URI));
            }
        });
        return resources;
    }

    /**
     * 生成swagger资源
     *
     * @param name
     * @param location
     * @return
     */
    private SwaggerResource swaggerResource(String name, String location) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion(NACOS_DEFAULT_SWAGGER_VERSION);
        return swaggerResource;
    }
}
